import createHandler from "./index"
import {getLoggedUser} from "./auth"
import {insertOne, remove, selectAll, selectOne} from "./fake-db"
import {v4} from "uuid"
import {now} from "../utils/time"

/**
 *  code: 7000-8000
 */


const creatOrder = createHandler((items, expectPrice, note) => {
    const curUser = getLoggedUser()
    if (!curUser) return {
        code: 101,
        msg: '登录过期'
    }
    let totalPrice = 0
    for (const item of items) {
        const { itemId, optionKey, number } = item
        const itemPO = selectOne('item', 'id', itemId)
        if (!itemPO) return {
            code: 7001,
            msg: '商品不存在'
        }
        const option = itemPO.options.find(option => option.key === optionKey)
        if (!option) return {
            code: 7002,
            msg: '配置不存在'
        }
        if (number > option.number) return {
            code: 7003,
            msg: '库存不足'
        }
        item.option = option
        totalPrice += option.price * number
    }
    if (expectPrice !== totalPrice) return {
        code: 7004,
        msg: '商品价格发生变动，请重新下单'
    }
    for (const {option, number} of items) {
        option.number -= number
    }
    const row = {
        id: v4(),
        uid: curUser.id,
        items: items.map(({itemId, option, number}) => ({
            item_id: itemId,
            option_key: option.key,
            number
        })),
        total_price: totalPrice,
        freight: 0,
        actual_price: totalPrice,
        note,
        is_payed: false,
        pay_way: null,
        created_at: now(),
        payed_at: null
    }
    insertOne('order', row)
    return {
        code: 0,
        data: row.id
    }
})

const getOrder = createHandler(orderId => {
    const order = selectOne('order', 'id', orderId)
    if (!order) return {
        code: 7005,
        msg: '订单不存在'
    }
    return {
        code: 0,
        data: order
    }
})

const payOrder = createHandler((orderId, payWay) => {
    const order = selectOne('order', 'id', orderId)
    if (!order) return {
        code: 7005,
        msg: '订单不存在'
    }
    if (order.is_payed) return {
        code: 7005,
        msg: '订单已支付，无需支付'
    }
    order.is_payed = true
    order.pay_way = payWay
    order.payed_at = now()
    return {
        code: 0,
    }
})

const getOrderDetail = createHandler(orderId => {
    const order = selectOne('order', 'id', orderId)
    if (!order) return {
        code: 7005,
        msg: '订单不存在'
    }
    if (!order.is_payed) return {
        code: 7005,
        msg: '订单还未支付'
    }
    const detailedItems = order.items.map(item => {
        const detailedItem = {
            itemId: item.item_id,
            optionKey: item.option_key,
            number: item.number
        }
        const itemPO = selectOne('item', 'id', item.item_id)
        if (!itemPO) {
            detailedItem.label = '【商品不存在】'
            detailedItem.optionName = '???'
            detailedItem.optionPrice = '?'
            return detailedItem
        }
        detailedItem.label = itemPO.label
        const option = itemPO.options.find(option => option.key === item.option_key)
        if (!option) {
            detailedItem.optionName = '【配置不存在】'
            detailedItem.optionPrice = '?'
            return detailedItem
        }
        detailedItem.img = option.img
        detailedItem.optionName = option.name
        detailedItem.optionPrice = option.price
        return detailedItem
    })
    return {
        code: 0,
        data: {...order, items: detailedItems}
    }
})

const getAllOrder = createHandler((orderId, uid, payWay) => {
    let orders = selectAll('order').map(order => {
        order = {...order}
        const user = selectOne('user', 'id', order.uid)
        order.uid = user ? user.uid : undefined
        if (!order.is_payed) order.pay_way = '未支付'
        order.status = order.is_payed ? '待发货' : '待支付'
        return order
    })
    if (orderId) orders = orders.filter(order => order.id === orderId)
    if (uid) orders = orders.filter(order => order.uid === uid)
    if (payWay) orders = orders.filter(order => order.pay_way.includes(payWay))
    return {
        code: 0,
        data: orders
    }
})

const deleteOrder = createHandler(orderId => {
    console.log(orderId)
    remove('order', 'id', orderId)
    return {
        code: 0
    }
})

export {creatOrder, getOrder, payOrder, getOrderDetail, getAllOrder, deleteOrder}